/*!
 @header CircleMemberListController.m
 @author 王 文彬
 @version 1.0.0 2013/01/29 Creation
 Copyright (c) 2013年 mypocketbaby. All rights reserved.
 */


#import "CircleMemberListController.h"
#import "Helper.h"
#import "Config.h"
#import "ABInvitationViewController.h"
#import "PersonalViewController.h"
#import "InvitationOptionsViewController.h"
#import "JMFBase.h"
#import "ASImageView.h"
#import <MessageUI/MessageUI.h>


//  -业务逻辑细节说明-
//
//  @abstract       view中有两个标签，“圈子好友”和“邀请中的”页，“圈子好友”显示的列表是用户已经在使用APP的圈友们，“邀请中的”显示的列表是用户已经邀请但是并没有注册使用APP的好友们。
//                  在“圈子好友”中，点击任意一行，会push到这个用户的个人信息页面；
//                  在“邀请中的”中，点击任意一行，会弹出一个actionsheet，让用户选择是否再次提醒好友加入使用我们的APP，提醒方式为电话提醒和短信提醒。
//                  点击“邀请”按钮，会push到邀请方式VC。

//  @discussion

//  @notes

//  -类修改日志-
//  修改人   修改时间     针对版本                   修改描述

//  周益    2013-05-29   1.0.0      将view改为商品管理一样的view，用于区别圈友和邀请中的好友


@interface CircleMemberListController ()<UIAlertViewDelegate>
{
    UIButton* _addButton;
    UIButton* _clearButton;
}
@end

@implementation CircleMemberListController

@synthesize circle = _circle;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //设置空白处背景颜色
    self.view.backgroundColor = _SYS_COLOR_BACKGROUND;
 
    //左侧按钮：返回
    UIButton* backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    //右侧按钮：添加
    _addButton = [Helper buttonWithStyle:ButtonStyleNavigationAdd];
    [_addButton addTarget:self action:@selector(addButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_addButton];
    
    //右按钮：清空所有记录
    _clearButton = [Helper buttonWithStyle:ButtonStyleNavigationClear];
    [_clearButton addTarget:self action:@selector(clearButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    
    //
    _invitedButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, _SYS_FRAME_WIDTH / 2, 40)];
    _invitedButton.titleLabel.font = _SYS_FONT_004;
    [_invitedButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_invitedButton setTitle:_L(@"btn_invited_01") forState:UIControlStateNormal];
    [_invitedButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_bg_001@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [_invitedButton addTarget:self action:@selector(invitedButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_invitedButton];
    
    
    //
    _invitingButton = [[UIButton alloc] initWithFrame:CGRectMake(_SYS_FRAME_WIDTH / 2, 0, _SYS_FRAME_WIDTH / 2, 40)];
    _invitingButton.titleLabel.font = _SYS_FONT_004;
    [_invitingButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_invitingButton setTitle:_L(@"btn_inviting_01") forState:UIControlStateNormal];
    [_invitingButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_bg_002@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [_invitingButton addTarget:self action:@selector(invitingButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_invitingButton];
    
    _baseRefreshVC = [[BaseRefreshViewController alloc] initWithStyle:UITableViewStylePlain];
    _baseRefreshVC.tableView.frame = CGRectMake(0, 40, _SYS_FRAME_WIDTH, _SYS_FRAME_HEIGHT - 44);
    
    if (iOS7) {
        _baseRefreshVC.tableView.frame = CGRectMake(0.0f, 40.0f, 320.0f, _SYS_FRAME_HEIGHT-22.0f);
    }
    _baseRefreshVC.disableTopRefresh = YES;
    _baseRefreshVC.tableView.delegate = self;
    _baseRefreshVC.tableView.dataSource = self;
    _baseRefreshVC.delegate = self;
    [self.view addSubview:_baseRefreshVC.tableView];
    
    _dataSource = [[NSMutableArray alloc] init];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self obtainFriendsWithStatusAndCheckId:nil];
}

//
- (void)setCircle:(NSDictionary *)circle
{
    _circle = circle;
    self.title = [circle valueForKey:@"name"];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return _dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        

        ASImageView* imageView = [[ASImageView alloc] initWithFrame:CGRectMake(8, 9, 25, 25)];
        imageView.image = [UIImage imageNamed:@"dynamic_btn_001"];
        
        [cell.contentView addSubview:imageView];
        
        
        UILabel* contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(45, 5, 170, 35)];
        contentLabel.font = _SYS_FONT_003;
        contentLabel.textColor = _SYS_COLOR_002;
        contentLabel.lineBreakMode = UILineBreakModeWordWrap;
        contentLabel.numberOfLines = 0;
        contentLabel.textColor = [UIColor blackColor];
        contentLabel.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:contentLabel];
        
        
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    NSDictionary* circle = [_dataSource objectAtIndex:indexPath.row];
    
    if (!_currentStatus) {
        //设置本行的row值给图片，图片点击的时候就可以通过_dataSource的row行获取到Circle对象
        [[cell.contentView.subviews objectAtIndex:0] setTag:indexPath.row];
        
        ASImageView *imageView = (ASImageView *)[cell.contentView.subviews objectAtIndex:0];
        
        [imageView setImageURL:[NSURL URLWithString:[circle objectForKey:@"previewAvatar"]] andSourceImageURL:nil forStyle:PictureStyleCircleMemberAvart];
//        ((AsyncImageView *)[cell.contentView.subviews objectAtIndex:0]).image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[circle objectForKey:@"previewAvatar"]]]];
        [((UILabel *)[cell.contentView.subviews objectAtIndex:1]) setText:[circle objectForKey:@"name"]];
    }
    else{
        ((ASImageView *)[cell.contentView.subviews objectAtIndex:0]).image = [UIImage imageNamed:@"dynamic_btn_001"];
        [((UILabel *)[cell.contentView.subviews objectAtIndex:1]) setText:[circle objectForKey:@"realName"]];
    }
    
    return cell;
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:true];

    if (!_currentStatus) {
        NSInteger personalID = [[[_dataSource objectAtIndex:indexPath.row] valueForKey:@"memberId"] integerValue];
        PersonalInfoViewController* personalInfoVC = [[PersonalInfoViewController alloc] initWithPersonId:personalID];
        [self.navigationController pushViewController:personalInfoVC animated:true];
    }
    
    else {
        
        _currentInvited = _dataSource[indexPath.row];

        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"" delegate:self cancelButtonTitle:nil destructiveButtonTitle:_L(@"title_invite_01") otherButtonTitles:_L(@"title_invite_02"), _L(@"btn_no_01"), nil];
        
        [actionSheet showInView:self.view];
    }
}

#pragma mark - 私有方法

/*!
 @abstract 获取好友列表信息
 根据变量_currentStatus值的不同来获取指定的成员列表，当_currentStatus为no时，表明用户点击了“圈子好友”按钮，此时应该请求用户圈子好友列表；否则表明用户点击了“邀请中的”按钮，此时应该请求邀请中的好友列表。
 */
- (void)obtainFriendsWithStatusAndCheckId:(NSString *)checkId
{
    
    NSString *url = nil;
    
    if (!_currentStatus) {
        url = _JSON_URL_CIRCLE_MEMBER_LIST;
        
    }
    else{
        url = _JSON_URL_CIRCLE_MEMBER_INVITE_LIST;
    }
    
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:url];
    request.hudOn = true;
    request.hudTitle = _L(@"title_loading_01");
    request.delegate = self;
    
    [request setValue:[_circle objectForKey:@"id"]  forParameter:@"circleId"];
    
    if (checkId != nil) {
        [request setValue:checkId forParameter:@"checkId"];
    }
    
    [request asynchronous];
}

/*!
 @abstract 清空tableview的datasource并刷新列表
 用户在切换“圈子好友“和”邀请中的“按钮时，要给用户感觉是列表先是空的，再会有数据。
 */
- (void)emptyTheTableData
{
    if (_dataSource != nil && _dataSource.count != 0) {
        
        [_dataSource removeAllObjects];
        [_baseRefreshVC.tableView reloadData];
    }
}

/*!
 @abstract 获取数据源最后一条数据的id
 @discussion 用于分页功能
 @result 数据源最后一条数据的id
 */
- (long)catchTheLastDataSourceId
{
    long lastID = 0;
    if (_dataSource.count > 0) {
        
        lastID = [_dataSource[_dataSource.count - 1][@"id"] integerValue];
    }
    return lastID;
}

#pragma mark - 自定义事件

/*!
 @abstract 返回按钮事件
 */
- (void) backButtonEvent
{
    //pop
    [self.navigationController popViewControllerAnimated:true];
}

/*!
 @abstract 添加按钮事件
 */
- (void)addButtonEvent
{
    //先要跳转到添加方式VC 包含从通讯录添加和输入手机号码添加
    
    InvitationOptionsViewController *invitationOptionsVC = [[InvitationOptionsViewController alloc] init];
    invitationOptionsVC.circle = _circle;
    invitationOptionsVC.navigationItem.title = self.title;
    [self.navigationController pushViewController:invitationOptionsVC animated:YES];
}

- (void)clearButtonEvent
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:_L(@"alert_126"), _circle[@"name"]] delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];
    
    [alertView show];
}

/*!
 @abstract ”圈子好友“按钮被点击。
 每次点击都要先清空tableview并reload，再向服务器请求数据
 */
- (void)invitedButtonEvent
{
    [_invitedButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_bg_001@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [_invitingButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_bg_002@2x" ofType:@"png"]] forState:UIControlStateNormal];
    _currentStatus = NO;
    
    [self emptyTheTableData];
    
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_addButton];
    
    [self obtainFriendsWithStatusAndCheckId:nil];
    
}

/*!
 @abstract ”邀请中的“按钮被点击。
 每次点击都要先清空tableview并reload，再向服务器请求数据
 */
- (void)invitingButtonEvent
{
    [_invitedButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_bg_002@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [_invitingButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_bg_001@2x" ofType:@"png"]] forState:UIControlStateNormal];
    _currentStatus = YES;
    
    [self emptyTheTableData];
    
    [self obtainFriendsWithStatusAndCheckId:nil];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_clearButton];
}

/*!
 @abstract 加载更多button被点击
 */
- (void)refresh
{
    
    //如果原数据源为空，就没必要加载更多
    if (_dataSource.count == 0) {
        
        [Helper showAllTextDialog:_L(@"title_nomore_01") inView:self.view];
        
        //设置成刷新模式为默认下拉刷新
        _baseRefreshVC.isFooterRefresh = NO;
        _baseRefreshVC.disableBottomRefresh = YES;
        
        return;
    }
    
    //获取此时数据源中最后一条记录的id
    
    NSString *checkId = [NSString stringWithFormat:@"%ld", [self catchTheLastDataSourceId]];
    
    //发送加载更多的请求,数据接受成功后，设置_reloading
    
    [self obtainFriendsWithStatusAndCheckId:checkId];
}


#pragma mark - JSONRequestDelegate

//
- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {

        //当为下拉刷新和初次进入时，应该对数据源进行格式化
        if (!_baseRefreshVC.isFooterRefresh) {
            if (_dataSource == nil) {
                _dataSource = [[NSMutableArray alloc] init];
                
            }else{
                [_dataSource removeAllObjects];
            }
            
            //下来刷新成功后，就将加载更多的按钮显示出来
            _baseRefreshVC.disableBottomRefresh = NO;
        }
        
        //加载更多后成功获取数据后，应先调用此方法，恢复到点击加载更多之前的页面状态
        [_baseRefreshVC stopRefresh];

        if ([(NSArray *)jmf.data count] == 0) {
            
            if (_baseRefreshVC.isFooterRefresh) {
                [Helper showAllTextDialog:_L(@"title_nomore_01") inView:self.view];
            }
            
            _baseRefreshVC.disableBottomRefresh = YES;
            
        }else{
            
            [_dataSource addObjectsFromArray:(NSArray *)jmf.data];
        }
        
        [_baseRefreshVC.tableView reloadData];
        
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
    
    //设置成刷新模式为默认下拉刷新
    _baseRefreshVC.isFooterRefresh = NO;
}

- (void)memberDidCleared:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        [Helper easyShowJMFStatus:jmf];
        
        [_dataSource removeAllObjects];
        
        [_baseRefreshVC.tableView reloadData];
        
        _baseRefreshVC.disableBottomRefresh = YES;
        
    }
}

//
- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}

#pragma mark - UIActionSheet Delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (_currentInvited == nil) {
        [Helper showAlertWithTitle:@"" andMessage:_L(@"alert_54")];
        return;
    }
    
    if (buttonIndex == 0) {
        
        NSMutableArray *mobileArray = [[NSMutableArray alloc] initWithObjects:[_currentInvited objectForKey:@"mobile"], nil];
        
        MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
        picker.messageComposeDelegate = (id)self;
        
        picker.body = _L(@"tpl_00");
        picker.recipients = mobileArray;
        
        [self presentModalViewController:picker animated:YES];
        
    }else if (buttonIndex == 1) {
        
        NSString *number = [NSString stringWithFormat:@"telprompt://%@", [_currentInvited objectForKey:@"mobile"]];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:number]];
        
    }
}

#pragma mark - SMS Delegate

// 短信发送状态通知协议方法
//
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    switch (result)
    {
        case MessageComposeResultCancelled:

            break;
        case MessageComposeResultSent: {
            
            //请求
            JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_CIRCLE_MEMBER_ADD];
            
            [request setValue:[_currentInvited objectForKey:@"realName"] forParameter:@"names"];
            [request setValue:[_currentInvited objectForKey:@"mobile"] forParameter:@"mobiles"];
            [request setValue:[_circle objectForKey:@"id"] forParameter:@"circleId"];
            NSDictionary* dict = [request synchronous];
            
            JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
            if (jmf.status == JMStatusSucceed) {

                [Helper showAllTextDialog:_L(@"title_loading_07") inView:self.view];    //正在发送
                
            }
            else {
                
                [Helper easyShowJMFStatus:jmf];
            }
        }
            
            break;
        case MessageComposeResultFailed:
            break;
        default:
            break;
    }
    
    //必须放在这里，要让case 1内的语句先执行，才能使viewDidAppear获取到正确的值
    [controller dismissModalViewControllerAnimated:true];
}


#pragma mark - UIAlertView Delegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_CIRCLE_MEMBER_INVITE_CLEAR];
        request.hudOn = true;
        request.hudTitle = _L(@"title_loading_01");
        request.delegate = self;
        
        [request setValue:_circle[@"id"] forParameter:@"circleId"];
        
        [request setSuccessSelector:@selector(memberDidCleared:)];
        [request asynchronous];

    }
}
@end
